package cn.iocoder.yudao.module.infra.controller.admin.base;

import cn.iocoder.yudao.framework.common.exception.BusinessException;
import cn.iocoder.yudao.framework.common.util.validation.ValidationUtils;
import cn.iocoder.yudao.framework.web.core.util.BaseController;
import cn.iocoder.yudao.module.infra.dal.dataobject.base.TreeDO;
import cn.iocoder.yudao.module.infra.service.base.TreeService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/infra/base/tree")
public class TreeController extends BaseController {

    @Resource
    private TreeService treeService;

    @GetMapping(value = "/listTreeType", produces = "application/json")
    public List<String> listTreeType() {
        return treeService.listTreeType();
    }

    @PostMapping(value = "/getTree", produces = "application/json")
    public List<TreeDO> getTree(String type) {
        TreeDO tree = treeService.getTreeByType(type);
        List<TreeDO> data = new ArrayList<>();
        data.add(tree);
        return data;
    }

    @PostMapping(value = "/listTree", produces = "application/json")
    public List<TreeDO> listTree(String type) {
        return treeService.listTreeByType(type);
    }

    @PostMapping(value = "/addTreeRoot", produces = "application/json")
    public String addTreeRoot(@RequestBody TreeDO root) {
        if (root == null) {
            throw new BusinessException("请求参数为空");
        }
        root.setCreator(getLoginUserId().toString());
        treeService.addTreeRoot(root);
        return "添加成功";
    }

    @PostMapping(value = "/addTreeNode", produces = "application/json")
    public String addTreeNode(@RequestBody TreeDO node) {
        ValidationUtils.validNotBeNull(node, "node");
        node.setCreator(getLoginUserId().toString());
        treeService.addTreeNode(node);
        return "添加成功";
    }

    @PostMapping(value = "/editTreeNode", produces = "application/json")
    public String editTreeNode(@RequestBody TreeDO node) {
        ValidationUtils.validNotBeNull(node, "node");
        node.setUpdater(getLoginUserId().toString());
        treeService.editTreeNode(node.getId(), node.getLabel(), node.getName(), node.getOrderNo(), node.getRemark(), node.getUpdater());
        return "更新成功";
    }

    @PostMapping(value = "/delTreeNode", produces = "application/json")
    public String delTreeNode(@RequestBody TreeDO node) {
        ValidationUtils.validNotBeNull(node, "node");
        treeService.delTreeNode(node.getId(), getLoginUserId().toString());
        return "删除成功";
    }

}
